<script setup>
import '@/uni_modules/uview-plus/index.scss'
import { onLoad, onLaunch, onShow, onHide, onReady, onUnload } from '@dcloudio/uni-app'
import { useSystemStore, useMemberStore, configWebsitStore } from '@/stores'
import { revisionsApi } from '@/services/my/tool-about-us'
let payload = null

function updateApp(data) {
  const platform = uni.getSystemInfoSync().platform //手机平台
  if (platform === 'android') {
    // requestNotifyPermission() // 安卓请求通知权限
    // #ifdef APP-PLUS || APP-ANDROID
    AndroidCheckUpdate(data)
    // #endif
  } else {
    // uni.showModal({
    //   title: '发现新版本 ' + data.version,
    //   content: '请到App store进行升级',
    //   showCancel: false,
    // })
    uni.showModal({
      title: '版本更新',
      content: '有新的版本发布，是否立即进行新版本下载？',
      confirmText: '立即更新',
      showCancel: false,
      success: (res) => {
        if (res.confirm) {
          let appleId = 6476603429
          plus.runtime.launchApplication(
            {
              action: `itms-apps://itunes.apple.com/cn/app/id${appleId}`,
            },
            function (e) {
              console.log('Open system default browser failed: ' + e.message)
            },
          )
        }
      },
    })
  }
}
onLaunch(() => {
  const selfVersionCode = uni.getSystemInfoSync().appVersion //当前App版本号
  revisionsApi({
    version: selfVersionCode,
  }).then((res) => {
    console.log(res)
    const newVersionName = res.data.version
    let selfArr = selfVersionCode?.split('.')
    let newArr = newVersionName?.split('.')
    if (res.data.is_update == 2) {
      // 强制更新
      if (Number(selfArr[0]) < Number(newArr[0])) {
        updateApp(res.data)
        return false
      }
      if (Number(selfArr[1]) < Number(newArr[1])) {
        updateApp(res.data)
        return false
      }
      if (Number(selfArr[2]) < Number(newArr[2])) {
        updateApp(res.data)
        return false
      } else {
        return false
      }
    }
  })

  let system = useSystemStore()
  uni.getSystemInfo({
    success: (e) => {
      system.setStatusHeight(e.statusBarHeight)
    },
  })
  // #ifdef APP-PLUS || APP-IOS || APP-ANDROID
  try {
    plus.screen.lockOrientation('portrait-primary') // 禁止横屏
    uni.setKeepScreenOn({
      keepScreenOn: true,
    })
    let system = useSystemStore()
    uni.getSystemInfo({
      success: (e) => {
        system.setStatusHeight(e.statusBarHeight)
      },
    })
  } catch (error) {
    console.log('APP-onLaunch-error', error)
  }
  // #endif
})

onShow(() => {
  // #ifdef APP-PLUS || APP-IOS || APP-ANDROID
  uni.onPushMessage((res) => {
    payload = JSON.parse(res?.data?.payload)
    console.log('收到推送消息1：', payload) //监听推送消息

    if (payload?.type?.startsWith('pages/')) {
      uni.switchTab({
        url: `${payload?.type}`,
      })
    } else {
      uni.navigateTo({
        url: `${payload?.type}?uid=${payload?.uid}&name=${payload?.name}&avatar=${payload?.avatar}&chat_type=${payload?.transaction_type}&childId=${payload?.child_id}`,
      })
    }
  })
  try {
    // setTimeout(function () {
    //   let pages = getCurrentPages()
    //   let currentPage = pages[pages?.length - 1]
    //   const route = `/${currentPage?.route}` // 当前页面路由
    //   let args = plus.runtime.arguments // 启动参数
    //   plus.runtime.arguments = null
    //   plus.runtime.arguments = ''
    //   console.log('args', args)
    //   if (args) {
    //     // 完整路径带参数
    //     let a = args?.split('//')
    //     let url = '/' + a[1]
    //     console.log(route)
    //     if (url && route != url) {
    //       console.log('path', url)
    //       uni.navigateTo({
    //         url,
    //       })
    //     }
    //   }
    // }, 1000)
  } catch (error) {
    console.log('APP-onShow-error', error)
  }
  /* #endif */
})

function AndroidCheckUpdate(data) {
  uni.showModal({
    title: '版本更新',
    content: 'APP有新版本发布，点击 立即更新 进行最新版本下载。',
    confirmText: '立即更新',
    cancelText: '稍后进行',
    showCancel: false,
    success: function (res) {
      if (res.confirm) {
        uni.showLoading({
          title: '安装包下载中……',
          mask: true,
        })
        uni.downloadFile({
          // 下载资源包
          url: data.apk_url,
          success: (downloadResult) => {
            uni.hideLoading()
            console.log('downloadResult', downloadResult)
            if (downloadResult.statusCode === 200) {
              uni.showLoading({
                title: '安装中……',
                mask: true,
              })
              plus.runtime.install(
                downloadResult.tempFilePath,
                {
                  // 安装资源包
                  force: false,
                },
                function () {
                  console.log('install success...')
                  plus.runtime.restart() // 重启APP
                },
                function (e) {
                  console.error('install fail...')
                },
              )
            }
          },
          fail() {
            uni.hideLoading()
          },
        })
      } else if (res.cancel) {
        console.log('稍后更新')
      }
    },
  })
}
</script>

<style lang="scss">
// 字体图标

@import 'static/iconfont/iconfont.css';
@import '@/styles/common.scss';
@import '@/styles/shop.scss';
@import '@/styles/fonts.scss';
@import '@/uni_modules/uview-plus/index.scss';
// @import 'animate.css'; // animate__animated
view,
navigator,
input,
scroll-view {
  box-sizing: border-box;
}

button::after {
  border: none;
}

swiper,
scroll-view {
  flex: 1;
  height: 100%;
  overflow: hidden;
}

image {
  width: 100%;
  // height: 100%;
  // vertical-align: middle;
}

input[type='text'],
input[type='password'],
textarea {
  -webkit-appearance: none;
  outline: none;
}

.fixed-btn {
  background: #fff;
  bottom: 0;
  height: calc(120rpx + env(safe-area-inset-bottom) / 2);
  left: 0;
  padding: 0 0 calc(env(safe-area-inset-bottom) / 2);
  position: fixed;
  width: 100vw;
  z-index: 998;
}

// 两行省略
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.flex {
  align-items: center;
  display: flex;
}

.flex-sub {
  flex: 1;
}

.bg-main.round {
  border-radius: 60rpx;
}

.bg-main {
  background-color: #00ad99;
  color: #fff;
}

.fixed-btn button {
  font-size: 28rpx;
  height: 90rpx;
  line-height: 90rpx;
  margin: 15rpx 30rpx;
}

// 两行省略
.ellipsis {
  overflow: hidden;
  text-overflow: ellipsis;
  display: -webkit-box;
  -webkit-line-clamp: 2;
  -webkit-box-orient: vertical;
}

.popupBottom {
  min-height: 55vh;
}

.container {
  background: #fff;
  min-height: 100vh;
}

.bgef {
  background: #efefef;
}

.popupBottom-header-title {
  color: #333;
  font-size: 30rpx;
  font-weight: 700;
  height: 110rpx;
  line-height: 110rpx;
  text-align: center;
}

.font-bg-red,
.font_bg-red {
  display: inline-block;
  align-items: center;
  background: #e93424;
  color: #fff;
  font-size: 20rpx;
  text-align: center;
  border-radius: 5rpx;
  padding: 0 4rpx;
  line-height: 28rpx;
  margin-right: 8rpx;
  border: 1px solid #e93424;
}

.font-bg-red {
  background-color: var(--view-theme);
  border: 1px solid var(--view-theme);
}

.p-index {
  .index-swiper {
    .input-class {
      width: 220rpx;
    }
  }
}

.line1 {
  overflow: hidden;
  text-overflow: ellipsis;
  white-space: nowrap;
}
</style>
